package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;

import com.alibaba.fastjson.JSONObject
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import groovy.json.*;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import cn.com.kh.getProperty;

/*
 * @purpose: 腾讯云短信发送接口
 * @示例报文：
 * */

/**
 *
 * @Title: BP_job_SmsSend
 * @Description: 宝安排水腾讯云短信发送接口对接
 * @author: chieh
 * @date 2020-08-05 12:28:00
 *
 */
public class BP_job_SmsSend implements CallBackInvoke{
	private static final Log log=LogFactory.getLog(BP_job_SmsSend.class);
	public void doCallBack(EliteBean eliteBean,String callBack,Map map,String paramString){

		log.debug("----------------------------------start BP_job_SmsSend from 开始发送短信 -----------------------------");//日志标识，方便查找
		//判断是否有需要发送的短信
		def getSmsSelectSQL = eliteBean.chaxun_sql("select DOCUMENTOUT_GUID,DOCUMENTTO,model_id as templateId,model_1 as msg_1,model_2 as msg_2,model_3 as msg_3,model_4 as msg_4,model_5 as msg_5 from documentout where ExpectedStartDate<=GETDATE() and STATUS=0 and response_msg is null","dataSource");
		log.debug("SQL获取数据:"+getSmsSelectSQL);
		if(getSmsSelectSQL.size() > 0) {
			log.debug("BP_job_SmsSend开始处理短信发送任务--------------------------");
			//获取配置信息
			int apiid = Integer.parseInt(getProperty.get("SMS.AppID"));
			String apikey = getProperty.get("SMS.AppKey");
			String smsSign = "宝安排水"; // 签名			
			log.debug("apiid:" + apiid+"	apikey:" + apikey);
		
			boolean sendMsgResult=false; //短信发送结果
			String cloudResponseStr=""; //腾讯云返回结果
			def returnMessage='';//返回信息
			def returnDealFlag="";//响应标识 1 成功，0 失败
			def returnDealMessage="";//响应信息
			
			String documentOutGUID="";//documentout表，主键，用于更新数据
			String DOCUMENTTO="";//手机号码
			int templateId=0;////腾讯云短信模板ID
			String msg_1 =""; //内容参数1
			String msg_2 =""; //内容参数2
			String msg_3 =""; //内容参数3
			String msg_4 =""; //内容参数4
			String msg_5 =""; //内容参数5
			try{
			for(int i=0;i<getSmsSelectSQL.size();i++) {
				documentOutGUID = getSmsSelectSQL.get(i).get("DOCUMENTOUT_GUID");
				DOCUMENTTO= getSmsSelectSQL.get(i).get("DOCUMENTTO");
				templateId=Integer.parseInt(getSmsSelectSQL.get(i).get("templateId"));;
				msg_1 =getSmsSelectSQL.get(i).get("msg_1");
				msg_2 =getSmsSelectSQL.get(i).get("msg_2");
				msg_3 =getSmsSelectSQL.get(i).get("msg_3");
				msg_4 =getSmsSelectSQL.get(i).get("msg_4");
				msg_5 =getSmsSelectSQL.get(i).get("msg_5");
				
				ArrayList<?> docParams = new ArrayList<?>();
				if(templateId==680764||templateId==715230||templateId==715232) {
					docParams.add(msg_1);
				}else if(templateId==680771||templateId==717766||templateId==680770) {
					docParams.add(msg_1);
					docParams.add(msg_2);
				}else if(templateId==680768||templateId==680769) {
					docParams.add(msg_1);
					docParams.add(msg_2);
					docParams.add(msg_3);
				}else if(templateId==680766||templateId==680767||templateId==717753) {
					docParams.add(msg_1);
					docParams.add(msg_2);
					docParams.add(msg_3);
					docParams.add(msg_4);
				}else if(templateId==717761) {
					docParams.add(msg_1);
					docParams.add(msg_2);
					docParams.add(msg_3);
					docParams.add(msg_4);
					docParams.add(msg_5);
				}
					try {
						
						SmsSingleSender ssender = new SmsSingleSender(apiid, apikey);
						// 签名参数未提供或者为空时，会使用默认签名发送短信
						SmsSingleSenderResult result = ssender.sendWithParam("86", DOCUMENTTO, templateId, docParams, smsSign, "", "");
						log.info("result:"+result);

						cloudResponseStr=result.toString();

						JSONObject reponseBodyJsonObject = JSONObject.parseObject(cloudResponseStr);
						String resultCode = reponseBodyJsonObject.getString("result");
						String resultMsg = reponseBodyJsonObject.getString("errmsg");

						if("0".equals(resultCode)) {
							sendMsgResult=true;
							returnDealFlag="1";
							returnDealMessage="腾讯云短信发送成功！";
						} else if("1025".equals(resultCode)){//手机号日频率限制
							sendMsgResult=false;
							returnDealFlag="8";
							returnDealMessage="腾讯云短信发送失败！"+java.net.URLDecoder.decode(resultMsg);
						}else if("1016".equals(resultCode)){//手机号格式错误
							sendMsgResult=false;
							returnDealFlag="9";
							returnDealMessage="腾讯云短信发送失败！"+java.net.URLDecoder.decode(resultMsg);
						}else {
							sendMsgResult=false;
							returnDealFlag="5";
							returnDealMessage="腾讯云短信发送失败！"+java.net.URLDecoder.decode(resultMsg);
						}
					} catch (HTTPException e) {
						// HTTP响应码错误
						sendMsgResult=false;
						returnDealMessage="HTTP响应码错误!";
						e.printStackTrace();
					} catch (JSONException e) {
						// json解析错误
						sendMsgResult=false;
						returnDealMessage="json解析错误!";
						e.printStackTrace();
					} catch (IOException e) {
						// 网络IO错误
						sendMsgResult=false;
						returnDealMessage="网络IO错误!";
						e.printStackTrace();
					}
			}
	
		} catch(SAXParseException) {
			log.error("异常",SAXParseException); //打印日志
			returnDealFlag="0";
			returnDealMessage="系统:接收的请求报文格式错误,无法解析数据!";
		}
		returnMessage="""{"dealFlag":"${returnDealFlag}","dealMessage":"${returnDealMessage}","cloudResponse":${cloudResponseStr}}""";
		
		eliteBean.update("update DocumentOut set response_msg = '"+returnMessage+"',Status = '"+returnDealFlag+"',TrialCount = TrialCount+1,LastTryDateTime=GETDATE(),FinishDateTime=GETDATE(),ModifiedDate=GETDATE()  where DocumentOut_GUID = '"+documentOutGUID+"'", "dataSource");
		log.debug("returnMessage:" + returnMessage+"	Status:" + returnDealFlag+"	documentOutGUID:" + documentOutGUID);
			
		log.debug(returnMessage); 
	}
		log.debug("BP_job_SmsSend当前无短信发送任务--------------------------");
		
	}

}
